package com.item.yxlottery.yxlottery.common;

/*
 *------------------------------
 * @创建者      Administrator
 * @创建时间    2016/11/16 10:49
 * @文件描述    自定义Application
 *------------------------------
 */

import android.app.Application;
import android.content.Context;

import com.item.yxlottery.yxlottery.service.LocationService;
import com.item.yxlottery.yxlottery.utils.ACache;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;


public class MyApplication extends Application {

    private static Context mContext;
    private final String TAG = "yxlottery";//自定义log的tag
    private static ACache mACache;
    private static LocationService mLocationService;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();

        initOkhttp();//初始化OKhttp网络框架

        loggerConfig();//Logger的配置

        Hawk.init(this).build();//初始化Hawk存储(可以当做一个简易的数据库使用,有增删改查功能)

        mACache = ACache.get(this);//缓存框架

        mLocationService = new LocationService(mContext);//初始化定位服务
    }

    private void loggerConfig() {
        Logger.init(TAG)
                .logLevel(LogLevel.FULL)//全部打印,  LogLevel.NONE(不打印log,发布时需要设置)
                .methodCount(3)//方法栈打印的个数,默认是2
                .methodOffset(2);//设置调用堆栈的函数偏移值,默认是0
    }

    private void initOkhttp() {
        CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));//持久化存储
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);//https访问设置(可访问所有的https)
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LoggerInterceptor(TAG))//自带的log输入
                .cookieJar(cookieJar)//cookice方式
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)//设置https访问
                .connectTimeout(20000L, TimeUnit.MILLISECONDS)//连接主机超时时长20s
                .readTimeout(20000L, TimeUnit.MILLISECONDS)//从主机读取数据超时时长20s
                .build();
        OkHttpUtils.initClient(okHttpClient);
    }

    /*- 获取Application context -*/
    public static Context getContext() {
        return mContext;
    }

    /*- 获取ACache -*/
    public static ACache getACache() {
        return mACache;
    }

    /*- 获取ACache -*/
    public static LocationService getLocationService() {
        return mLocationService;
    }
}
